package com.ly.jvm;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import	java.util.concurrent.atomic.AtomicInteger;
import	java.util.concurrent.TimeUnit;

class Source {

//    public int number;
    volatile int number;


    AtomicInteger count = new AtomicInteger();

    public void addNumber() {
        this.number += 1;
    }

    public void addAtomic() {
        count.addAndGet(1);
    }
}


public class VolatileDemo {

    public static void main(String[] args) throws InterruptedException {
        Source source = new Source();
        CyclicBarrier cyclicBarrier = new CyclicBarrier( 20,() -> {
            System.out.println(source.number);
            System.out.println(source.count);
            System.out.println("end");
        });
        for(int i=0;i<20;i++) {
            new Thread( ()-> {
                for(int j=0;j<1000;j++) {
                    source.addNumber();
                    source.addAtomic();

                }
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();
        }

//        while(Thread.activeCount()>2) {
//            Thread.yield();
//        }
//        System.out.println(source.number);
//        System.out.println(source.count);
    }

    public static void keJianXing() {
        Source source = new Source();
        new Thread( ()->{
            System.out.println(source.number);
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            source.addNumber();
            System.out.println(source.number);
        },"A").start();

        while(source.number == 0) {

        }

        System.out.println("----");
    }
}
